import { useCookies } from "@vueuse/integrations/useCookies";
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router';

export function useMain() {

    const router = useRouter();
    const cookie = useCookies();
    const route = useRoute();
    const activeTab = ref(route.path)

    const tabList = ref([
        {
            title: '后台首页',
            path: '/',
        }
    ])
    /** 点击菜单，添加 tab */
    const addTab = (tab) => {
        console.log('打印tab',tab);
        let oneTab = (tabList.value.findIndex(t => t.path === tab.path)) === -1
        if (oneTab) {
            tabList.value.push(tab);
        }
        // console.log(JSON.stringify(tabList.value));
        cookie.set("tabList", tabList.value);
    }
    // 删除功能
    const removeTab = (t) => {
        console.log('打印删除的tab', t);
        let a = activeTab.value;
        let tbList = tabList.value;
        if (t === a) {
            tbList.forEach((item, index) => {
                // console.log(item);
                if (item.path === t) {
                    // 判断数组中是否是最后一项，如果是最后一项，那他的下一项就不存在，则自动跳转到上一项，如果不是最后一项，则跳转到下一项
                    let haveIndex = tbList[index + 1] ? index + 1 : index - 1
                    a = tbList[haveIndex].path;
                }
            })
        }
        activeTab.value = a;
        // 进行导航的删除操作
        tabList.value = tabList.value.filter(item => item.path !== t);
        // 存储到cookies中
        cookie.set("tabList", tabList.value);
    }
    /** 清除所有 和 清除其他 */
    const handleCommand = (e) => {
        switch (e) {
            case 'clearAll':
                tabList.value = tabList.value.filter(item => item.path === '/');
                cookie.set("tabList", tabList.value);
                break;
            case 'clearOther':
                tabList.value = tabList.value.filter(item => item.path === '/' || item.path === activeTab.value);
                cookie.set("tabList", tabList.value);
                break;
            default:
                break;
        }
    }


    const changeTab = (t) => {
        router.push(t);

    }
    // 初始化标签导航列表
    const initTabLists = () => {
        let tbs = cookie.get("tabList");
        // 如果存在 tabList的token 就进行 赋值。
        if (tbs) {
            tabList.value = tbs;
        }
    }

    initTabLists();
    return {
        tabList,
        activeTab,
        addTab,
        removeTab,
        handleCommand,
        changeTab,
        initTabLists,
    }
}